package com.tangxz.chat.modules.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * @author: 唐小尊
 * @email: 1171702529@qq.com
 * @cate: 2021/04/17 16:18
 */
@Slf4j
@Component//当成组件处理
@Order(value = 1)//这里表示启动顺序
public class WebSocketServer implements CommandLineRunner {
    private int port = 2828;
    EventLoopGroup mainGroup = new NioEventLoopGroup();
    EventLoopGroup subGroup = new NioEventLoopGroup();
    ChannelFuture sync = null;

    public void startChatNettyServer() throws Exception {
        //创建服务器类
        ServerBootstrap server = new ServerBootstrap();
        server.group(mainGroup,subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new WSServerInitialzer());
        log.info("\n启动server");
        ChannelFuture future = server.bind(port).sync();
        //当服务器同步通道关闭，就继续往下执行
        sync = future.channel().closeFuture().sync();
    }

    @PreDestroy
    public void destory() {
        if (sync != null) {
            log.info("Netty Server close");
            mainGroup.shutdownGracefully();
            subGroup.shutdownGracefully();
        }
    }

    //异步启动
    @Async
    @Override
    public void run(String... args) throws Exception {
        startChatNettyServer();
    }
}
